//
//  LLPlayManager.swift
//  新印象
//
//  Created by wyl on 2016/12/22.
//  Copyright © 2016年 魏延龙. All rights reserved.
//

import UIKit
import FreeStreamer

protocol LLPlayManagerDelegate {
    func currentValueDidUpdate(duration : durationSong)
    func totalValueDidUpdate(duration : durationSong)
    func progressValue(value : Float)
}

class LLPlayManager: NSObject {
    var FSAudio = FSAudioStream()
    var url : String!
    var timer : Timer?
    var delegate : LLPlayManagerDelegate?
    
    
    func playUrl() {
        FSAudio.play(from: URL(string: url))
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(currentProgressValue), userInfo: nil, repeats: true)
        timer?.fire()
    }
    
    func pause() {
        FSAudio.pause()
    }
    
    func play() {
        FSAudio.play()
    }
    
    func stop() {
        timer?.invalidate()
        FSAudio.stop()
    }
    
    func next() {
        stop()
        playUrl()
    }
    
    func last() {
        stop()
        playUrl()
    }
    
    func currentProgressValue() {
        let position = FSAudio.currentTimePlayed
        var duration = durationSong()
        duration.minute = position.minute
        duration.second = position.second
        delegate?.currentValueDidUpdate(duration: duration)
        totalValue()
        progressValue()
    }
     
    func totalValue() {
        let position = FSAudio.duration
        var duration = durationSong()
        duration.minute = position.minute
        duration.second = position.second
        delegate?.totalValueDidUpdate(duration: duration)
    }
    
    func progressValue() {
        let currentPosition = FSAudio.currentTimePlayed
        let position = FSAudio.duration
        let value = (Float(currentPosition.minute * 60 + currentPosition.second)/Float(position.minute * 60 + position.second))
        delegate?.progressValue(value: Float(value))
    }
    
}

struct durationSong {
    var minute : UInt32?
    var second : UInt32?
}
